package com.example.lab17_p01_mediademo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.VideoView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		copyFromAssetToSDCard();
	}

	// public void playVideo(View v) {
	// String url =
	// "http://channelz2.r15s91.vcdn.vn/zv/18b37ff14af9ff78be84ffa328a0d343/54a26990/2014/12/30/8/1/81d21be5cd03bf457df70eae0e4e838c.mp4";
	// Uri uri = Uri.parse(url);
	// final VideoView videoView = (VideoView) findViewById(R.id.videoView1);
	// final ProgressDialog progressDialog = new ProgressDialog(this);
	// progressDialog.setMessage("loading.....");
	// progressDialog.show();
	// MediaController mediaController = new MediaController(this);
	// mediaController.setAnchorView(videoView);
	// videoView.setMediaController(mediaController);
	// videoView.requestFocus();
	// videoView.setVideoURI(uri);
	// videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
	//
	// @Override
	// public void onPrepared(MediaPlayer mp) {
	// progressDialog.dismiss();
	// videoView.start();
	// }
	// });
	// }

	String folderPath = Environment.getExternalStorageDirectory()
			.getAbsolutePath() + "/Musics";

	void copyFromAssetToSDCard() {
		File f = new File(folderPath);
		if (!f.exists()) {
			f.mkdir();
		}

		String[] listFiles;
		AssetManager assetManager = getAssets();
		try {
			listFiles = assetManager.list("");
			InputStream in = null;
			OutputStream out = null;
			for (int i = 0; i < listFiles.length; i++) {
				if (!new File(listFiles[i]).isFile()) {
					continue;
				}
				in = assetManager.open(listFiles[i]);
				File file = new File(folderPath, listFiles[i]);
				out = new FileOutputStream(file);
				copyFile(in, out);
			}
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	void copyFile(InputStream in, OutputStream out) throws IOException {
		byte[] b = new byte[4096];
		int n;
		while ((n = in.read(b)) > 0) {
			out.write(b, 0, n);
		}
		out.flush();
	}

	public void playVideo(View v) {
		// String url =
		// "http://channelz2.r15s91.vcdn.vn/zv/18b37ff14af9ff78be84ffa328a0d343/54a26990/2014/12/30/8/1/81d21be5cd03bf457df70eae0e4e838c.mp4";
		// String url = "android.resource://" + getPackageName() + "/" +
		// R.raw.famous;
		String url = folderPath + "/giacmocothat.mp3";

		Uri uri = Uri.parse(url);

		final VideoView videoView = (VideoView) findViewById(R.id.videoView1);
		final ProgressDialog progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Buffering...");
		progressDialog.show();

		// Tao ra MediaController
		MediaController mediaController = new MediaController(this);
		// Neo vao VideoView
		mediaController.setAnchorView(videoView);
		videoView.setMediaController(mediaController);

		videoView.requestFocus();
		videoView.setVideoURI(uri);

		videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

			@Override
			public void onPrepared(MediaPlayer mp) {
				progressDialog.dismiss();
				videoView.start();
			}
		});
	}

	public void stopMusic(View v) {
		mediaPlayer.stop();
		seekBar.setProgress(0);
	}

	public void seekToRight(View v) {
		int curr = mediaPlayer.getCurrentPosition();
		int newPosition = curr + 5 * duration / 100;
		mediaPlayer.seekTo(newPosition);
	}

	public void seekToLeft(View v) {
		int curr = mediaPlayer.getCurrentPosition();
		int newPosition = curr - 5 * duration / 100;
		mediaPlayer.seekTo(newPosition);
	}

	MediaPlayer mediaPlayer;
	int duration;
	SeekBar SeekBar;
	SeekBar seekBar;

	class UpdateSeekBar extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... arg0) {
			while (mediaPlayer.isPlaying()) {
				publishProgress();
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			seekBar.setProgress(mediaPlayer.getCurrentPosition());
		}
	}

	public void playMusic(View v) {
		String url = "android.resource://" + getPackageName() + "/"
				+ R.raw.giacmocothat;
		Uri uri = Uri.parse(url);
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		try {
			mediaPlayer.setDataSource(this, uri);
			mediaPlayer.prepare();
			mediaPlayer.start();
			duration = mediaPlayer.getDuration();

			seekBar = (SeekBar) findViewById(R.id.seekBar1);
			seekBar.setMax(duration);

			new UpdateSeekBar().execute();

			seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
				}

				@Override
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromUser) {
					mediaPlayer.seekTo(progress);
				}
			});

		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
